<template>
  <div class="crud-demo">
    <h2>CRUD Example with Form and Table</h2>
    

    
    <!-- 表格部分 -->
    <div class="table-section">
      <el-card>
        <UXTable
          @register="registerTable"
          @selection-change="handleSelectionChange"
        >
          <!-- Custom action column -->
          <template #action="{ row }">
                <TableAction
                  :actions="[
                    {
                      label: 'View',
                      onClick: () => handleView(row),
                      type: 'primary',
                      size: 'small'
                    },
                    {
                      label: 'Edit',
                      onClick: () => handleEdit(row),
                      type: 'warning',
                      size: 'small'
                    },
                    {
                      label: 'Delete',
                      onClick: () => handleDelete(row),
                      type: 'danger',
                      size: 'small',
                      popConfirm: {
                        title: 'Are you sure you want to delete this record?',
                        confirm: () => confirmDelete(row)
                      }
                    }
                  ]"
                />
              </template>
        
        </UXTable>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h } from 'vue'
import { ElMessage, ElMessageBox,ElTag } from 'element-plus'
import { 
  UXTable, 
  TableAction, 
  UXForm, 
  useUXTable, 
  useUXForm,
  type TableColumn,
  type ApiFunction,
  type FetchParams,
  type FetchResult,
  type FormSchema
} from '@axewo/ux-element'

// Selected rows
const selectedRows = ref<any[]>([])

// Form state
const formState = reactive({
  isEdit: false,
  currentId: null as number | null,
})

const formTitle = computed(() => {
  return formState.isEdit ? 'Edit User' : 'Add User'
})

// Form schemas
const formSchemas = reactive<FormSchema[]>([
  {
    field: 'name',
    component: 'Input',
    label: 'Name',
    // rules: [{ required: true, message: 'Please enter name', trigger: 'blur' }],
    colProps: { span: 12 }
  },
  {
    field: 'age',
    component: 'InputNumber',
    label: 'Age',
    componentProps: {
      min: 1,
      max: 120
    },
    colProps: { span: 12 }
  },
  {
    field: 'gender',
    component: 'RadioGroup',
    label: 'Gender',
    options: [
      { label: 'Male', value: 'Male' },
      { label: 'Female', value: 'Female' },
      { label: 'Other', value: 'Other' }
    ],
    colProps: { span: 12 }
  },
  {
    field: 'status',
    component: 'RadioGroup',
    label: 'Status',
    options: [
      { label: 'Enabled', value: 1 },
      { label: 'Disabled', value: 0 }
    ],
    colProps: { span: 12 }
  },
  {
    field: 'phone',
    component: 'Input',
    label: 'Phone',
    colProps: { span: 12 }
  },
  {
    field: 'email',
    component: 'Input',
    label: 'Email',
    colProps: { span: 12 }
  },
  {
    field: 'address',
    component: 'Input',
    label: 'Address',
    componentProps: {
      type: 'textarea',
      rows: 2
    },
    colProps: { span: 24 }
  }
])

// Search params
const searchParams = reactive({
  name: '',
  status: undefined as number | undefined,
})

// Table column definitions
const columns: TableColumn[] = [
  {
    prop: 'name',
    label: 'Name',
    width: 120
  },
  {
    prop: 'age',
    label: 'Age',
    width: 80
  },
  {
    prop: 'gender',
    label: 'Gender',
    width: 80
  },
  {
    prop: 'phone',
    label: 'Phone',
    width: 130
  },
  {
    prop: 'email',
    label: 'Email',
    width: 180,
    showOverflowTooltip: true
  },
  {
    prop: 'address',
    label: 'Address',
    minWidth: 180,
    showOverflowTooltip: true
  },
  {
    prop: 'status',
    label: 'Status',
    width: 100,
    render: ({ text }) => {
      if (text === 1) {
        return h(ElTag, { type: 'success' }, () => 'Enabled');
      } else {
        return h(ElTag, { type: 'danger' }, () => 'Disabled');
      }
    }
  },
  {
    prop: 'createTime',
    label: 'Created Time',
    width: 180
  }
]

// Mock data base
let mockUserDatabase = [
  {
    id: 1,
    name: 'John Doe',
    age: 25,
    gender: 'Male',
    phone: '13812345678',
    email: 'john.doe@example.com',
    address: 'New York, USA',
    status: 1,
    createTime: '2023-01-15 09:30:12'
  },
  {
    id: 2,
    name: 'Jane Smith',
    age: 32,
    gender: 'Female',
    phone: '13987654321',
    email: 'jane.smith@example.com',
    address: 'Los Angeles, USA',
    status: 0,
    createTime: '2023-02-20 15:45:30'
  },
  {
    id: 3,
    name: 'Bob Johnson',
    age: 28,
    gender: 'Male',
    phone: '13567891234',
    email: 'bob.johnson@example.com',
    address: 'Chicago, USA',
    status: 1,
    createTime: '2023-03-10 11:20:05'
  },
  {
    id: 4,
    name: 'Alice Brown',
    age: 35,
    gender: 'Female',
    phone: '13654789012',
    email: 'alice.brown@example.com',
    address: 'San Francisco, USASan Francisco, USASan Francisco, USASan Francisco, USASan Francisco, USASan Francisco, USASan Francisco, USA',
    status: 1,
    createTime: '2023-04-05 16:10:45'
  },
  {
    id: 5,
    name: 'Charlie Wilson',
    age: 26,
    gender: 'Male',
    phone: '13912345678',
    email: 'charlie.wilson@example.com',
    address: 'Boston, USA',
    status: 0,
    createTime: '2023-05-18 10:35:22'
  }
]

// Create more data for display
for (let i = 6; i <= 50; i++) {
  const base = mockUserDatabase[i % 5]
  mockUserDatabase.push({
    ...base,
    id: i,
    name: `User ${i}`,
    email: `user${i}@example.com`,
    createTime: new Date().toISOString().split('T').join(' ').substr(0, 19)
  })
}

// Mock API function
const fetchUserList = async (params: FetchParams) => {
  const { page, pageSize, name, status } = params
  
  // Simulate API request delay
  await new Promise(resolve => setTimeout(resolve, 500))
  
  // Filter data based on search params
  let filteredData = [...mockUserDatabase]
  
  if (name) {
    filteredData = filteredData.filter(item => 
      item.name.toLowerCase().includes(name.toLowerCase())
    )
  }
  
  if (status !== undefined) {
    filteredData = filteredData.filter(item => item.status === status)
  }
  
  // Sort by id in descending order
  filteredData.sort((a, b) => b.id - a.id)
  
  // Calculate pagination
  const total = filteredData.length
  const startIndex = (page - 1) * pageSize
  const endIndex = startIndex + pageSize
  const paginatedData = filteredData.slice(startIndex, endIndex)
  
  // Return data in expected format
  return {
    code: 200,
    data:{
      page: page,
      pageSize: pageSize,
      list: paginatedData,
      total: total
    }
  }
}


// Use table hook
const [registerTable] = useUXTable({
  api: fetchUserList,
  title:"用户列表",
  columns: columns,
  formConfig: {
    labelWidth: '100px',
    schemas: formSchemas
  },
  immediate: true,
  searchInfo: searchParams,
  showSelection: true,
  showIndex: true,

  fetchSetting: {
    pageField: 'page',
    sizeField: 'pageSize',
    listField: 'data.list',
    totalField: 'data.total',
    resultField: 'data'
  }
})



// Selection change handler
const handleSelectionChange = (rows: any[]) => {
  console.log('Selected rows:', rows)
  selectedRows.value = rows
}

// View handler
const handleView = (row: any) => {
  // ElMessage.info(`View user: ${row.name}`)
  console.log('View details:', row)
}

// Add new user
const handleAdd = () => {
  formState.isEdit = false
  formState.currentId = null
  // resetFields()
  // clearValidate()
}

// Edit handler
const handleEdit = (row: any) => {
  formState.isEdit = true
  formState.currentId = row.id
}

// Delete handler
const handleDelete = (row: any) => {
  console.log('Preparing to delete:', row)
}

// Confirm delete handler
const confirmDelete = (row: any) => {
  deleteUser(row.id)
  ElMessage.success(`User deleted: ${row.name}`)
}

// Batch delete handler
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('Please select at least one row to delete')
    return
  }
  
  ElMessageBox.confirm(
    `Are you sure you want to delete ${selectedRows.value.length} selected records?`,
    'Warning',
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  ).then(() => {
    const ids = selectedRows.value.map(row => row.id)
    ids.forEach(id => deleteUser(id))
    ElMessage.success(`Successfully deleted ${ids.length} records`)
  }).catch(() => {
    ElMessage.info('Delete canceled')
  })
}

// Delete user from database
const deleteUser = (id: number) => {
  const index = mockUserDatabase.findIndex(item => item.id === id)
  if (index !== -1) {
    mockUserDatabase.splice(index, 1)
  }
}

// Form submit handler
const handleSubmit = async (values: Record<string, any>) => {
  try {
    await validate()
    
    if (formState.isEdit && formState.currentId) {
      // Update existing user
      const index = mockUserDatabase.findIndex(item => item.id === formState.currentId)
      if (index !== -1) {
        mockUserDatabase[index] = {
          ...mockUserDatabase[index],
          ...values,
        }
        ElMessage.success(`Successfully updated user: ${values.name}`)
      }
    } else {
      // Add new user
      const newId = Math.max(...mockUserDatabase.map(item => item.id)) + 1
      const newUser = {
        id: newId,
        ...values,
        createTime: new Date().toISOString().split('T').join(' ').substr(0, 19)
      }
      mockUserDatabase.unshift(newUser)
      ElMessage.success(`Successfully added user: ${values.name}`)
    }
    
    // Reset form and reload table
    resetFields()
    formState.isEdit = false
    formState.currentId = null
    apiState.reload()
  } catch (error) {
    console.error('Form validation failed:', error)
    ElMessage.error('Please complete the required fields')
  }
}

// Form reset handler
const handleReset = () => {
  resetFields()
  clearValidate()
}
</script>

<style scoped>
.crud-demo {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .left {
  font-size: 16px;
  font-weight: 500;
}

.card-header .right {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

h2 {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}
</style> 